<!--  -->
<template>
   <div class="login_container">
     <TopNavBar></TopNavBar>
      <!-- banner -->

      <div class="archive-banner banner">
        <vue-particles
          color="#FF0088"
          :particleOpacity="1"
          :particlesNumber="80"
          shapeType="circle"
          :particleSize="4"
          linesColor="#FF0088"
          :linesWidth="1"
          :lineLinked="true"
          :lineOpacity="0.7"
          :linesDistance="150"
          :moveSpeed="3"
          :hoverEffect="true"
          hoverMode="grab"
          :clickEffect="true"
          clickMode="push"
        ></vue-particles>
        <h1 class="banner-title">归档</h1>
      </div>
      <div class="login_box">
      <!-- 头像区域 -->
      <div class="avatar_box">
       <img src="http://localhost:8001/img/user/avatar/acquiescent.png" width="108" alt="">
      </div>
        <!-- 登录表单区域 -->
        <el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules" label-width="0px" class="login_form">
          <!-- 用户名 -->
          <el-form-item prop="account">
            <el-input v-model="loginForm.account" placeholder="请输入用户名或手机号" prefix-icon="el-icon-user-solid"></el-input>
          </el-form-item>
          <!-- 密码 -->
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" placeholder="请输入密码" prefix-icon="el-icon-moon-night" type="password"></el-input>
          </el-form-item>
          <el-form-item prop="VerifyCode">
            <el-input v-model="loginForm.VerifyCode" placeholder="请输入验证码" prefix-icon="el-icon-picture-outline-round" style="width: 50%"></el-input>
            <img v-bind:src='src' @click="getVerifyCode()" width="130px" height="35px" style="float: right;cursor:pointer;margin-right: 40px" />
          </el-form-item>
          <!-- 按钮区域 -->
          <el-form-item class="btns">
            <el-button type="success" @click="handleCreate">注册</el-button>
            <el-button type="primary" @click="login">登录</el-button>
            <el-button type="info" @click="resetLoginForm">忘记密码</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 注册弹层-->
      <div class="add-form">
        <el-dialog title="注册用户" :visible.sync="dialogFormVisible">
          <el-form ref="registForm" :model="formData" :rules="loginFormRules" label-position="right"
                   label-width="100px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="用户名" prop="username">
                  <el-input label="请输入用户名" v-model="formData.username"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="密码" prop="password">
                  <el-input v-model="formData.password"/>
                </el-form-item>
              </el-col>
            </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="phone">
                <el-input v-model="formData.phone"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="验证码" prop="verify">
                <el-input
                  v-model="formData.verify"
                  type="text"
                  placeholder="手机验证码"
                />
                <el-button
                  @click.native.prevent="bindforgetSendCode(1)"
                  class="codebtn"
                  :disabled="disabled"
                >{{ btnText }}</el-button>
              </el-form-item>
              <!-- 验证码完毕 -->
            </el-col>
          </el-row>
            <el-col :span="24">
              <el-form-item label="头像地址">
                <el-input v-model="formData.avatar" disabled/>
              </el-form-item>
            </el-col>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="regist()">确定</el-button>
          </div>
        </el-dialog>
      </div>
     <!-- 忘记密码弹层 -->
      <div class="add-form">
        <el-dialog title="忘记密码" :visible.sync="dialogFormVisible2">
          <el-form ref="registForm" :model="formData" :rules="loginFormRules" label-position="right"
                   label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="phone">
                <el-input v-model="formData.phone" placeholder="请输入手机号码"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="新密码" prop="password">
                <el-input v-model="formData.password" placeholder="请输入新的密码"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="验证码" prop="VerifyCode">
                <el-input v-model="formData.VerifyCode" placeholder="请输入验证码"/>
                <el-button
                  @click.native.prevent="bindforgetSendCode(2)"
                  class="codebtn"
                  :disabled="disabled"
                >{{ btnText }}</el-button>
              </el-form-item>
            </el-col>
          </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="Forget()">确定</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
</template>

<script>
import TopNavBar from '../../components/layout/TopNavBar'

export default {
  // 注册组件
  components: {
    TopNavBar
  },
  data () {
    return {
      src: 'http://localhost:9527/service-user/user/generate',
      imageUrl: '',
      verifyCode: '',
      Message: '',
      formData: {
        VerifyCode: '',
        username: '',
        password: '',
        phone: '',
        avatar: '默认头像'
      },
      dialogFormVisible: false, // 增加表单是否可见
      dialogFormVisible2: false, // 增加表单是否可见
      // 这是登录表单的数据绑定对象
      loginForm: {
        account: '',
        password: '',
        VerifyCode: ''
      },
      // 这是表单的验证规则对象
      loginFormRules: {
        //验证手机号码是否合法
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        // 验证用户名是否合法
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        // 验证登录手机号或名称是否合法
        account: [
          { required: true, message: '请输入登录名称', trigger: 'blur' },
          { min: 3, max: 11, message: '长度在 3 到 11 个字符', trigger: 'blur' }
        ],
        // 验证密码是否合法
        password: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        // 验证码
        VerifyCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      //   验证码按钮
      type: "",
      btnText: "获取验证码",
      disabled: false,
    }
  },
  created () {
    this.getVerifyCode()
  },
  methods: {
    // 发送验证码
    bindforgetSendCode(type) {
      if(type===1){
        this.$refs.registForm.validate((valid) => {
          if(valid){
            this.$http.get("/service-user/user/queryphone/"+this.formData.phone).then((data) => {
              if (data.data.flag) {
                const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
                if (reg.test(this.formData.phone)) {
                  this.$http.post("/service-user/user/SendMessage/"+this.formData.phone).then((res) => {
                    if(res.data.flag){
                      this.$message.error("短信验证码发送成功!")
                      this.Message=res.data.phone;
                      alert(this.Message)
                      this.disabled = true;
                      this.btnText = "请稍候...";
                      setTimeout(() => {
                        this.doLoop(60);
                      }, 500);
                    }else{
                      this.$message.error(res.data.error)
                    }
                  })
                }else{
                  this.$message.error("请输入正确的手机号码!")
                }
              }else{
                this.$message.error("该手机号码已被注册,请输入可用手机号!")
              }
            })
          }else{
            this.$message.error("请先填写注册信息!")
          }
        })
      }else{
        this.$refs.registForm.validate((valid) => {
          if(valid){
            this.$http.get("/service-user/user/queryphone/"+this.formData.phone).then((data) => {
              if (!data.data.flag) {
                const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
                if (reg.test(this.formData.phone)) {
                  this.$http.post("/service-user/user/SendMessage/"+this.formData.phone).then((res) => {
                    if(res.data.flag){
                      this.$message.error("短信验证码发送成功!")
                      this.Message=res.data.phone;
                      alert(this.Message)
                      this.disabled = true;
                      this.btnText = "请稍候...";
                      setTimeout(() => {
                        this.doLoop(60);
                      }, 500);
                    }else{
                      this.$message.error(res.data.error)
                    }
                  })
                }else{
                  this.$message.error("请输入正确的手机号码!")
                }
              }else{
                this.$message.error("未找到该手机号注册的用户!")
              }
            })
          }
        })
      }

    },
    // 手机验证码的倒计时
    doLoop: function (seconds) {
      seconds = seconds ? seconds : 60;
      this.btnText = seconds + "s后获取";
      let countdown = setInterval(() => {
        if (seconds > 0) {
          this.btnText = seconds + "s后获取";
          --seconds;
        } else {
          this.btnText = "获取验证码";
          this.disabled = false;
          clearInterval(countdown);
        }
      }, 1000);
    },
    getCode(){

    },
    //get错误
     getVerifyCode () {
       var num=Math.ceil(Math.random()*10);//生成一个随机数（防止缓存）
       this.src = "http://localhost:9527/service-user/user/generate?" + num;
    },
    //点击重置按钮，重置登录表单
    resetLoginForm () {
        this.dialogFormVisible2 = true
    },
    //弹出添加窗口
    handleCreate () {
      this.dialogFormVisible = true
    },
    regist () {
      // 进行表单校验
      this.$refs.registForm.validate((valid) => {
        if (valid) {
          const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
          if (reg.test(this.formData.phone)) {
            this.$http.get("/service-user/user/queryname/"+this.formData.username).then((res) => {
              if (res.data.flag) {
                this.$http.get("/service-user/user/queryphone/"+this.formData.phone).then((data) => {
                  if (data.data.flag) {
                    // 表单校验通过，发ajax请求，把数据录入至后台处理
                    if(this.Message==this.formData.verify){
                      console.log(this.formData)
                      //验证手机号是否被注册
                      this.$http.post("/service-user/user/register/"+this.formData.username+"/"+this.formData.password+"/"+this.formData.avatar+"/"+this.formData.phone).then((res) => {
                        // 关闭新增窗口
                        this.dialogFormVisible = false
                        if (res.data.flag) {
                          // 弹出提示信息
                          this.$message({
                            message: '注册成功，快来登录吧！',
                            type: 'success'
                          })
                        } else { // 执行失败
                          this.$message.error(res.data.message)
                        }
                      })
                    }else{
                      this.$message.error("短信验证码错误,请重新输入!")
                    }
                  } else { // 执行失败
                    this.$message.error("该手机号已被注册,请重新输入手机号!")
                    this.formData.phone=''
                  }
                })
              } else { // 执行失败
                this.$message.error("用户名已被使用,请重新输入用户名!")
                this.formData.username=''
              }
            })
          }else{//手机号码非法
            this.$message.error('请输入正确的手机号码')
          }

        } else { // 校验不通过
          this.$message.error('校验失败，请检查输入格式')
          return false
        }
      })
    },
    Forget(){
      this.$refs.registForm.validate((valid) => {
        if(valid){
          const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
          if (reg.test(this.formData.phone)) {
            //验证手机号是否被注册
            this.$http.get("/service-user/user/queryphone/"+this.formData.phone).then((res) => {
              if (!res.data.flag) {
                const user=res.data.user
                user.password=this.formData.password
                if(this.Message!=''){
                  if(this.Message==this.formData.VerifyCode){
                    this.$http.put('/service-user/user/update', user).then((res) => {
                      if (res.data.flag) {//修改成功!
                        // 弹出提示信息
                        this.$message({
                          message: '修改密码成功!,请登录！',
                          type: 'success'
                        })
                        setTimeout(() => {
                          window.location.reload()
                        }, 500);
                        this.setlogin()
                      } else { // 执行失败
                        this.$message.error(res.data.message)
                      }
                    })
                  }else{//验证码错误
                    this.$message.error('请输入正确的验证码!')
                  }
                }else {
                  this.$message.error('请先获取验证码!')
                }
              }else{//通过手机号码未找到用户
                this.$message.error('未找到该手机号注册的用户!')
              }
            })
          }else{//非法的手机号码
            this.$message.error('请输入正确的手机号码!')
          }
        }else { // 校验不通过
          this.$message.error('校验失败，请检查输入格式')
          return false
        }
      })
    },
    login () {
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return
        // console.log('===>' + JSON.stringify(this.loginForm))
        // console.log('===>' + this.$encrypTion(param))
        // console.log('param2' + param2)
        const { data: res } = await this.$http.post('/service-user/user/login/'+this.loginForm.account+'/'+this.loginForm.password+'/'+this.loginForm.VerifyCode)
        console.log(res.flag)
        if (res.flag !== true) {
          this.$message.error(res.message)
          this.loginForm.VerifyCode=''
          await this.getVerifyCode()
        } else {
          this.$message.success('登录成功')
          // 1. 将登录成功之后的 token，保存到客户端的 sessionStorage 中
          //   1.1 项目中出了登录之外的其他API接口，必须在登录之后才能访问
          //   1.2 token 只应在当前网站打开期间生效，所以将 token 保存在 sessionStorage 中
          window.sessionStorage.setItem('token', res.code)
          window.sessionStorage.setItem('user', JSON.stringify(res.user))
          // 2. 通过编程式导航跳转到后台主页，路由地址是 /home
          await this.$router.push('/welcome')
          // 刷新页面，删除vuex数据
          setTimeout(() => {
            window.location.reload()
          }, 100)
        }
      })
    }
  }
}

</script>

<style  scoped>
    .banner-title {
    animation: title-scale 1s;
    position: absolute;
    top: 25rem;
    padding: 0 0.5rem;
    width: 100%;
    font-size: 2.5rem;
    text-align: center;
    color: #eee;
  }
  .archive-banner {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    background: url("../../assets/images/loginpsc.jpg") center center /
    cover no-repeat;
    background-color: #49b1f5;
  }
  .login_container {
    background-color: #2b4b6b;
    height: 100%;
  }
  .login_box {
    width: 450px;
    height: 360px;
    background-color: #fff;
    border-radius: 3px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
  .avatar_box {
    height: 130px;
    width: 130px;
    border: 1px solid #eee;
    border-radius: 50%;
    padding: 10px;
    box-shadow: 0 0 10px #ddd;
    position: absolute;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    /* img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background-color: #eee;
    } */
  }
  .login_form {
    position: absolute;
    bottom: 0;
    width: 100%;
    padding: 0 20px;
    box-sizing: border-box;
  }

  .btns {
    display: flex;
    justify-content: flex-end;
  }
  .avatar-uploader .el-upload {
    border: 5px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 60px;
    height: 60px;
    display: block;
  }
    #particles-js{
      width: 100%;
      height: 900px;
      position: absolute;
    }
</style>
